package com.sdk.springbootdynamicschedule.dynamictwo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/tasks")
public class Task2Controller {

    @Autowired
    private TaskService taskService;

    // 请求参数DTO（推荐使用）
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class TaskRequest {
        private String taskId;
        private String cron;
    }

    @PostMapping("/schedule")
    public ResponseEntity<String> scheduleTask(@RequestBody TaskRequest request) {
        try {
            taskService.addTask(request.getTaskId(), request.getCron());
            return ResponseEntity.ok("任务[" + request.getTaskId() + "]已创建");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("创建失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/cancel/{taskId}")
    public ResponseEntity<String> cancelTask(@PathVariable String taskId) {
        taskService.cancelTask(taskId);
        return ResponseEntity.ok("任务[" + taskId + "]已取消");
    }

    @GetMapping("/list")
    public Map<String, String> listTasks() {
        return taskService.getTasks().keySet().stream()
                .collect(Collectors.toMap(
                        id -> id,
                        Function.identity()
                ));
    }
}
